import { createRouter, createWebHistory} from 'vue-router'
import { isUserLoggedIn } from '../service/user.ts';

import Index  from '../pages/Index.vue';
import Team from '../pages/Team.vue';
import LoginPage from '../pages/Login.vue';
import UserPage from "../pages/UserPage.vue";
import SearchPage from '../pages/SearchPage.vue';
import TeamAddPage from '../pages/TeamAddPage.vue';
import UserEditPage from  '../pages/EditPage.vue';
import TeamJoinPage from "../pages/TeamJoinPage.vue";
import UserUpdatePage from '../pages/UserUpdatePage.vue';
import TeamUpdatePage from "../pages/TeamUpdatePage.vue";
import SearchResultPage from '../pages/SearchResult.vue';
import TeamCreatePage from "../pages/TeamCreatePage.vue";

const routes = [
    {  path: '/',meta:{title:"伙伴匹配"}, component: Index},
    { path: '/team',meta:{title:"找队伍"} ,  component: Team  },
    { path: '/user',meta:{ title:"个人主页", requiresAuth: true},component:UserPage },
    { path: '/login',meta:{ title:"登录"},component: LoginPage },
    { path: '/search',meta:{ title:"找朋友"}, component:SearchPage },
    { path: '/team/add',meta:{ title:"创建队伍", requiresAuth: true}, component: TeamAddPage },
    { path: '/user/edit',meta:{ title:"个人信息编辑", requiresAuth: true}, component:UserEditPage },
    { path: '/team/join',meta:{ title:"用户加入的队伍", requiresAuth: true}, component: TeamJoinPage },
    { path: '/team/update',meta:{ title:"更新队伍", requiresAuth: true}, component: TeamUpdatePage },
    { path: '/user/list',meta:{ title:"用户列表"}, component:SearchResultPage },
    { path: '/user/update',meta:{ title:"个人信息更新", requiresAuth: true}, component: UserUpdatePage },
    { path: '/team/create',meta:{ title:"用户创建的队伍", requiresAuth: true}, component: TeamCreatePage },
]

 const router = createRouter({
    history: createWebHistory(),
    routes,
})
router.beforeEach((to, from, next) => {
    // 从路由元信息中获取标题
    const pageTitle = to.meta.title

    // 如果有标题就设置，否则使用默认标题
    if (pageTitle) {
        document.title = `${pageTitle} `
    } else {
        document.title = '伙伴匹配' // 默认标题
    }

    // 检查是否需要登录
    if (to.meta.requiresAuth) {
        if (isUserLoggedIn()) {
            next(); // 已登录，继续访问
        } else {
            // 未登录，跳转到登录页
            next('/login');
        }
    } else {
        next(); // 不需要登录，继续访问
    }
})


export default router